#include "light_control.h"
#include "led_control.h"
#include "myfont.h"
#include "ac_control.h"
#include "smart_home_ui.h"
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

// 声明外部LED图标
extern const lv_img_dsc_t LED;

// 声明强制清屏函数
extern void force_clear_screen_ghosting(void);

// 界面元素
static lv_obj_t *light_screen = NULL;
static lv_obj_t *label_title = NULL;
static lv_obj_t *btn_back = NULL;
static lv_obj_t *btn_next = NULL;  // 向右滑动到空调界面的按钮
static lv_obj_t *light_time_label = NULL;
static lv_obj_t *light_date_label = NULL;
static lv_timer_t *light_timer_update = NULL;

// 四个LED控制框和标签
static lv_obj_t *led_control_boxes[4];
static lv_obj_t *led_icons[4];
static lv_obj_t *led_labels[4];
static const char *led_names[4] = {"客厅", "卧室", "厨房", "阳台"};
static const int led_gpios[4] = {LED1_GPIO, LED2_GPIO, LED3_GPIO, LED4_GPIO};

// 全局LED状态数组，用于与首页同步
static bool global_led_states[4] = {false, false, false, false};

// 灯光界面时间更新回调函数
static void light_update_time_task(lv_timer_t *timer) {
    static time_t last_update_s = 0;
    static char last_date_str[32] = "";
    static char last_time_str[32] = "";
    
    time_t now;
    time(&now);
    
    // 当timer为NULL时（手动调用），强制更新一次
    bool force_update = (timer == NULL);
    
    // 仅在秒有变化时更新，避免重复重绘
    if(!force_update && now == last_update_s) return;
    last_update_s = now;
    if(light_date_label == NULL || light_time_label == NULL) return; // 确保标签已创建
    
    time_t raw_time;
    struct tm *time_info;
    char date_str[32];
    char time_str[32];
    
    raw_time = now;
    time_info = localtime(&raw_time);
    
    // 分别格式化日期和时间
    strftime(date_str, sizeof(date_str), "%Y-%m-%d", time_info);
    strftime(time_str, sizeof(time_str), "%H:%M:%S", time_info);
    
    // 设置日期和时间标签文本
    if(force_update || strcmp(last_date_str, date_str) != 0) {
        lv_label_set_text(light_date_label, date_str);
        strcpy(last_date_str, date_str);
    }
    if(force_update || strcmp(last_time_str, time_str) != 0) {
        lv_label_set_text(light_time_label, time_str);
        strcpy(last_time_str, time_str);
    }
}

// LED控制框点击回调函数
static void led_box_event_cb(lv_event_t *e) {
    lv_obj_t *obj = lv_event_get_target(e);
    lv_event_code_t code = lv_event_get_code(e);
    
    if(code == LV_EVENT_CLICKED) {
        // 找到是哪个LED控制框
        for(int i = 0; i < 4; i++) {
            if(obj == led_control_boxes[i]) {
                // 切换状态
                bool new_state = !global_led_states[i];
                
                // 控制实际的LED
                if(led_set_state(led_gpios[i], new_state) == 0) {
                    // 更新全局状态
                    global_led_states[i] = new_state;
                    
                    // 更新控制框颜色和图标
                    if(new_state) {
                        // 开启状态 - 暖黄色
                        lv_obj_set_style_bg_color(led_control_boxes[i], lv_color_hex(0xF39C12), LV_PART_MAIN);
                        lv_obj_set_style_border_color(led_control_boxes[i], lv_color_hex(0xE67E22), LV_PART_MAIN);
                        // 图标亮黄色调
                        lv_obj_set_style_img_recolor_opa(led_icons[i], LV_OPA_30, LV_PART_MAIN);
                        lv_obj_set_style_img_recolor(led_icons[i], lv_color_hex(0xFFD700), LV_PART_MAIN);
                    } else {
                        // 关闭状态 - 深灰色
                        lv_obj_set_style_bg_color(led_control_boxes[i], lv_color_hex(0x2C3E50), LV_PART_MAIN);
                        lv_obj_set_style_border_color(led_control_boxes[i], lv_color_hex(0x34495E), LV_PART_MAIN);
                        // 图标灰色调
                        lv_obj_set_style_img_recolor_opa(led_icons[i], LV_OPA_70, LV_PART_MAIN);
                        lv_obj_set_style_img_recolor(led_icons[i], lv_color_hex(0x7F8C8D), LV_PART_MAIN);
                    }
                    
                    // 更新标签
                    char label_text[32];
                    snprintf(label_text, sizeof(label_text), "%s", led_names[i]);
                    if(led_labels[i]) lv_label_set_text(led_labels[i], label_text);
                    
                    // 同步到首页
                    sync_light_states_to_homepage();
                } else {
                    // LED控制失败，显示错误
                    char error_text[32];
                    snprintf(error_text, sizeof(error_text), "%s: 错误", led_names[i]);
                    if(led_labels[i]) lv_label_set_text(led_labels[i], error_text);
                }
                break;
            }
        }
    }
}

// 返回按钮回调
static void back_btn_event_cb(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_CLICKED) return;
    
    // 同步灯光状态到首页
    sync_light_states_to_homepage();
    
    // 确保有足够的时间完成同步
    usleep(10000);  // 10ms延迟
    
    // 使用安全的返回方式，避免在事件回调中直接删除当前屏幕
    return_to_smart_home_ui();
}

// 延迟切换到空调界面的回调函数
static void delayed_ac_switch_cb(lv_timer_t *timer) {
    cleanup_light_control_ui();
    force_clear_screen_ghosting();
    create_ac_control_screen();
    lv_timer_del(timer);  // 删除定时器
}

// 下一页按钮回调（切换到空调界面）
static void next_btn_event_cb(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_CLICKED) return;
    
    // 延迟切换到空调控制界面
    lv_timer_create(delayed_ac_switch_cb, 5, NULL);
}

// 滑动事件处理函数
static void swipe_event_cb(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    
    if(code == LV_EVENT_GESTURE) {
        lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
        if(dir == LV_DIR_RIGHT) {
            // 向右滑动，延迟切换到空调控制界面
            lv_timer_create(delayed_ac_switch_cb, 5, NULL);
        }
    }
}

// 创建灯光控制界面
void create_light_control_screen(void) {
    // 清理旧的对象引用
    light_screen = NULL;
    label_title = NULL;
    btn_back = NULL;
    btn_next = NULL;
    light_time_label = NULL;
    light_date_label = NULL;
    if(light_timer_update) {
        lv_timer_del(light_timer_update);
        light_timer_update = NULL;
    }
    for(int i = 0; i < 4; i++) {
        led_control_boxes[i] = NULL;
        led_icons[i] = NULL;
        led_labels[i] = NULL;
    }
    
    // 初始化LED控制
    led_init();
    

    
    // 创建新的灯光屏幕
    light_screen = lv_obj_create(NULL);
    lv_obj_set_style_bg_color(light_screen, lv_color_hex(0x2c3e50), LV_PART_MAIN);
    lv_obj_set_style_bg_opa(light_screen, LV_OPA_COVER, LV_PART_MAIN);
    lv_obj_clear_flag(light_screen, LV_OBJ_FLAG_SCROLLABLE);
    
    // 添加滑动手势支持
    lv_obj_add_event_cb(light_screen, swipe_event_cb, LV_EVENT_GESTURE, NULL);

    // 标题
    label_title = lv_label_create(light_screen);
    lv_obj_set_style_text_font(label_title, &lv_font_source_han_sans_bold_20, LV_PART_MAIN);
    lv_obj_set_style_text_color(label_title, lv_color_hex(0xecf0f1), LV_PART_MAIN);
    lv_label_set_text(label_title, "灯光控制");
    lv_obj_align(label_title, LV_ALIGN_TOP_MID, 0, 6);

    // 返回按钮（左上角）
    btn_back = lv_btn_create(light_screen);
    lv_obj_set_size(btn_back, 72, 40);
    lv_obj_align(btn_back, LV_ALIGN_TOP_LEFT, 12, 10);
    lv_obj_set_style_bg_color(btn_back, lv_color_hex(0x34495e), 0);
    lv_obj_set_style_radius(btn_back, 8, 0);
    lv_obj_set_style_border_width(btn_back, 0, 0);
    lv_obj_t *lbl_back = lv_label_create(btn_back);
    lv_obj_set_style_text_font(lbl_back, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(lbl_back, lv_color_hex(0xFFFFFF), 0);
    lv_label_set_text(lbl_back, LV_SYMBOL_LEFT " 返回");
    lv_obj_center(lbl_back);
    lv_obj_add_event_cb(btn_back, back_btn_event_cb, LV_EVENT_ALL, NULL);

    // 下一页按钮（右上角）
    btn_next = lv_btn_create(light_screen);
    lv_obj_set_size(btn_next, 72, 40);
    lv_obj_align(btn_next, LV_ALIGN_TOP_RIGHT, -12, 10);
    lv_obj_set_style_bg_color(btn_next, lv_color_hex(0x34495e), 0);
    lv_obj_set_style_radius(btn_next, 8, 0);
    lv_obj_set_style_border_width(btn_next, 0, 0);
    lv_obj_t *lbl_next = lv_label_create(btn_next);
    lv_obj_set_style_text_font(lbl_next, &lv_font_source_han_sans_bold_20, 0);
    lv_obj_set_style_text_color(lbl_next, lv_color_hex(0xFFFFFF), 0);
    lv_label_set_text(lbl_next, LV_SYMBOL_LEFT " 空调");
    lv_obj_center(lbl_next);
    lv_obj_add_event_cb(btn_next, next_btn_event_cb, LV_EVENT_ALL, NULL);

    // 添加时间显示（中间顶部）
    light_date_label = lv_label_create(light_screen);
    lv_obj_set_style_text_font(light_date_label, &lv_font_source_han_sans_bold_20, LV_PART_MAIN);
    lv_obj_set_style_text_color(light_date_label, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_label_set_text(light_date_label, "加载中...");
    lv_obj_align(light_date_label, LV_ALIGN_TOP_MID, 0, 60);

    light_time_label = lv_label_create(light_screen);
    lv_obj_set_style_text_font(light_time_label, &lv_font_source_han_sans_bold_20, LV_PART_MAIN);
    lv_obj_set_style_text_color(light_time_label, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_label_set_text(light_time_label, "加载中...");
    lv_obj_align_to(light_time_label, light_date_label, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);

    // 创建四个LED控制区域
    // 创建一个容器来放置LED控制
    lv_obj_t *led_container = lv_obj_create(light_screen);
    lv_obj_set_size(led_container, 800, 380);  // 调整容器尺寸适应布局
    lv_obj_align(led_container, LV_ALIGN_CENTER, 0, 20);   // 向上移动一些
    lv_obj_set_style_bg_color(led_container, lv_color_hex(0x34495e), LV_PART_MAIN);
    lv_obj_set_style_radius(led_container, 10, LV_PART_MAIN);
    lv_obj_set_style_border_width(led_container, 0, LV_PART_MAIN);
    lv_obj_set_style_shadow_width(led_container, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_all(led_container, 15, LV_PART_MAIN);  // 减少内边距
    lv_obj_clear_flag(led_container, LV_OBJ_FLAG_SCROLLABLE);   // 禁用滚动

    // 移除LED灯控制标题，直接显示控制框

    // 创建4个LED控制框，2x2布局（扩大尺寸）
    for(int i = 0; i < 4; i++) {
        int row = i / 2;
        int col = i % 2;
        int x_offset = col == 0 ? -180 : 180;  // 适应屏幕尺寸的水平间距
        int y_offset = 15 + row * 170;         // 优化垂直间距确保标签可见

        // 创建LED控制框（更大的正方形）
        led_control_boxes[i] = lv_obj_create(led_container);
        lv_obj_set_size(led_control_boxes[i], 120, 120);  // 减小尺寸避免遮挡标签
        lv_obj_align(led_control_boxes[i], LV_ALIGN_TOP_MID, x_offset, y_offset);
        lv_obj_set_style_radius(led_control_boxes[i], 15, LV_PART_MAIN);
        lv_obj_set_style_border_width(led_control_boxes[i], 3, LV_PART_MAIN);
        lv_obj_set_style_shadow_width(led_control_boxes[i], 8, LV_PART_MAIN);
        lv_obj_set_style_shadow_color(led_control_boxes[i], lv_color_hex(0x000000), LV_PART_MAIN);
        lv_obj_set_style_shadow_opa(led_control_boxes[i], 30, LV_PART_MAIN);
        lv_obj_clear_flag(led_control_boxes[i], LV_OBJ_FLAG_SCROLLABLE);
        lv_obj_add_event_cb(led_control_boxes[i], led_box_event_cb, LV_EVENT_CLICKED, NULL);

        // 设置初始颜色状态 - 使用最新的状态值
        bool current_state = get_light_state(i);  // 获取最新状态
        
        // 调试输出：显示界面创建时的状态
        printf("DEBUG: 灯光界面创建 - 灯%d: get_light_state(%d)=%s, global_led_states[%d]=%s\n", 
               i+1, i, current_state ? "开" : "关", i, global_led_states[i] ? "开" : "关");
        
        if(current_state) {
            // 开启状态 - 暖黄色
            lv_obj_set_style_bg_color(led_control_boxes[i], lv_color_hex(0xF39C12), LV_PART_MAIN);
            lv_obj_set_style_border_color(led_control_boxes[i], lv_color_hex(0xE67E22), LV_PART_MAIN);
        } else {
            // 关闭状态 - 深灰色
            lv_obj_set_style_bg_color(led_control_boxes[i], lv_color_hex(0x2C3E50), LV_PART_MAIN);
            lv_obj_set_style_border_color(led_control_boxes[i], lv_color_hex(0x34495E), LV_PART_MAIN);
        }

        // 在控制框内创建LED图标
        led_icons[i] = lv_img_create(led_control_boxes[i]);
        lv_img_set_src(led_icons[i], &LED);  // 使用自定义LED图标
        lv_obj_set_size(led_icons[i], 70, 70);   // 适应120x120控制框的图标尺寸
        
        // 根据状态设置图标颜色滤镜 - 使用最新的状态值
        if(current_state) {
            // 开启状态 - 正常显示（亮黄色调）
            lv_obj_set_style_img_recolor_opa(led_icons[i], LV_OPA_30, LV_PART_MAIN);
            lv_obj_set_style_img_recolor(led_icons[i], lv_color_hex(0xFFD700), LV_PART_MAIN);
        } else {
            // 关闭状态 - 灰色调
            lv_obj_set_style_img_recolor_opa(led_icons[i], LV_OPA_70, LV_PART_MAIN);
            lv_obj_set_style_img_recolor(led_icons[i], lv_color_hex(0x7F8C8D), LV_PART_MAIN);
        }
        lv_obj_center(led_icons[i]);

        // 创建LED标签（控制框下方）
        led_labels[i] = lv_label_create(led_container);
        lv_obj_set_style_text_font(led_labels[i], &lv_font_source_han_sans_bold_20, LV_PART_MAIN);
        lv_obj_set_style_text_color(led_labels[i], lv_color_hex(0xFFFFFF), LV_PART_MAIN);
        lv_obj_set_style_text_align(led_labels[i], LV_TEXT_ALIGN_CENTER, LV_PART_MAIN);
        lv_label_set_text(led_labels[i], led_names[i]);
        lv_obj_align_to(led_labels[i], led_control_boxes[i], LV_ALIGN_OUT_BOTTOM_MID, 0, 10);
    }

    // 创建时间更新定时器
    light_timer_update = lv_timer_create(light_update_time_task, 1000, NULL);
    // 立即更新一次时间
    light_update_time_task(NULL);
    
    // 从首页同步LED状态
    sync_light_states_from_homepage();
    
    // 使用安全的屏幕切换方式，避免段错误
    // 使用快速淡入动画，提供更流畅的切换体验
    lv_scr_load_anim(light_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
    
    // 让LVGL自动处理旧屏幕清理，避免手动删除导致的内存问题
}

// 清理灯光控制界面
void cleanup_light_control_ui(void) {
    // 清理定时器
    if(light_timer_update) {
        lv_timer_del(light_timer_update);
        light_timer_update = NULL;
    }
    
    // 清理对象指针
    light_screen = NULL;
    label_title = NULL;
    btn_back = NULL;
    btn_next = NULL;
    light_time_label = NULL;
    light_date_label = NULL;
    
    for(int i = 0; i < 4; i++) {
        led_control_boxes[i] = NULL;
        led_icons[i] = NULL;
        led_labels[i] = NULL;
    }
}

// 获取LED状态
bool get_light_state(int light_index) {
    if(light_index >= 0 && light_index < 4) {
        return global_led_states[light_index];
    }
    return false;
}

// 直接设置全局LED状态数组（用于开机时初始化）
void set_global_led_state(int light_index, bool state) {
    if(light_index >= 0 && light_index < 4) {
        printf("DEBUG: set_global_led_state - 灯%d: %s -> %s\n", 
               light_index + 1, global_led_states[light_index] ? "开" : "关", state ? "开" : "关");
        global_led_states[light_index] = state;
    }
}

// 设置LED状态
void set_light_state(int light_index, bool state) {
    if(light_index >= 0 && light_index < 4) {
        printf("DEBUG: set_light_state - 灯%d: %s -> %s\n", 
               light_index + 1, global_led_states[light_index] ? "开" : "关", state ? "开" : "关");
        global_led_states[light_index] = state;
        
        // 同步更新首页对应的全局变量
        extern bool global_light1_state;
        extern bool global_light2_state;
        extern bool global_light3_state;
        extern bool global_light4_state;
        
        switch(light_index) {
            case 0: global_light1_state = state; break;
            case 1: global_light2_state = state; break;
            case 2: global_light3_state = state; break;
            case 3: global_light4_state = state; break;
        }
        
        // 如果灯光界面已创建，同步控制框状态
        if(led_control_boxes[light_index] != NULL) {
            // 更新控制框颜色和图标
            if(state) {
                // 开启状态 - 暖黄色
                lv_obj_set_style_bg_color(led_control_boxes[light_index], lv_color_hex(0xF39C12), LV_PART_MAIN);
                lv_obj_set_style_border_color(led_control_boxes[light_index], lv_color_hex(0xE67E22), LV_PART_MAIN);
                // 图标亮黄色调
                lv_obj_set_style_img_recolor_opa(led_icons[light_index], LV_OPA_30, LV_PART_MAIN);
                lv_obj_set_style_img_recolor(led_icons[light_index], lv_color_hex(0xFFD700), LV_PART_MAIN);
            } else {
                // 关闭状态 - 深灰色
                lv_obj_set_style_bg_color(led_control_boxes[light_index], lv_color_hex(0x2C3E50), LV_PART_MAIN);
                lv_obj_set_style_border_color(led_control_boxes[light_index], lv_color_hex(0x34495E), LV_PART_MAIN);
                // 图标灰色调
                lv_obj_set_style_img_recolor_opa(led_icons[light_index], LV_OPA_70, LV_PART_MAIN);
                lv_obj_set_style_img_recolor(led_icons[light_index], lv_color_hex(0x7F8C8D), LV_PART_MAIN);
            }
            
            // 更新标签
            if(led_labels[light_index]) lv_label_set_text(led_labels[light_index], led_names[light_index]);
        }
    }
}

// 注意：sync_light_states_to_homepage 和 sync_light_states_from_homepage 
// 函数在 smart_home_ui.c 中实现
